package com.kifas.controller;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.kifas.entity.GroupEntity;
import com.kifas.entity.MenuEntity;
import com.kifas.model.xml.MenuModel;
import com.kifas.model.xml.PersistStatus;
import com.kifas.service.EntityServiceManager;


@Component
@Scope("prototype")
@Path("/Menus")
public class MenuController {

	private static Logger log = Logger.getLogger(MenuController.class);

	@Context
	UriInfo uriInfo;

	@Autowired
	private EntityServiceManager entityManager;
	
	@POST
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	public PersistStatus insert(JAXBElement<MenuModel> xml) {
		MenuModel model = xml.getValue();
		try {
			GroupEntity group = entityManager.getGroupById(model.getIdGroup());
			entityManager.persist(new MenuEntity(null, model.getName(), model.getTitle(), model.getUrl(), model.isEnable(), group));
		} catch (Exception e) {
			log.error("Can not persist Menu entity.", e);
			return new PersistStatus("MenuEntity", "failed", "Can not persist Menu Entity");
		}
		return new PersistStatus("MenuEntity", "success");
	}
	
	@GET
	@Path("Group/{id}")
	@Produces(MediaType.APPLICATION_XML)
	public List<MenuModel> getMenuByGroupId(@PathParam("id") Long idGroup) {
		return transformList(entityManager.getMenusByGroupId(idGroup));
	}
	
	private List<MenuModel> transformList(List<MenuEntity> menus) {
		List<MenuModel> models = new ArrayList<MenuModel>();
		for(MenuEntity menu : menus) {
			models.add(transform(menu));
		}
		return models;
	}

	private MenuModel transform(MenuEntity menu) {
		return new MenuModel(menu.getIdMenu(), menu.getName(), menu.getTitle(), menu.getUrl(), menu.isEnable(), menu.getGroup().getIdGroup());
	}
}
